package com.codingclub.application.controller;

import com.codingclub.application.convert.SubjectLabelDTOConverter;
import com.codingclub.application.dto.SubjectLabelDTO;
import com.codingclub.common.entity.Result;
import com.codingclub.common.enums.ErrCode;
import com.codingclub.common.enums.IsDeleteEnum;
import com.codingclub.common.exception.BusinessException;
import com.codingclub.infra.basic.entity.SubjectLabel;
import com.codingclub.infra.basic.service.SubjectLabelService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/subject/label")
public class SubjectLabelController {

    @Resource
    private SubjectLabelService subjectLabelService;

    /**
     * 新增标签
     */
    @PostMapping("/add")
    public Result<Boolean> add(@RequestBody SubjectLabelDTO subjectLabelDTO) {
        subjectLabelDTO.validatorParam(subjectLabelDTO, true);
        SubjectLabel subjectLabel = SubjectLabelDTOConverter.INSTANCE.convertDtoToEntity(subjectLabelDTO);

        boolean b = subjectLabelService.insert(subjectLabel);
        return Result.ok(b);
    }

    /**
     * 更新标签
     */
    @PostMapping("/update")
    public Result<Boolean> update(@RequestBody SubjectLabelDTO subjectLabelDTO) {
        subjectLabelDTO.validatorParam(subjectLabelDTO, false);
        SubjectLabel subjectLabel = SubjectLabelDTOConverter.INSTANCE.convertDtoToEntity(subjectLabelDTO);
        boolean b = subjectLabelService.update(subjectLabel);
        return Result.ok(b);
    }

    /**
     * 删除标签
     */
    @PostMapping("/delete")
    public Result<Boolean> delete(@RequestBody SubjectLabelDTO subjectLabelDTO) {
        if (subjectLabelDTO == null && subjectLabelDTO.getId() == null) {
            throw new BusinessException(ErrCode.PARAMS_ERROR);
        }
        SubjectLabel subjectLabel = new SubjectLabel();
        subjectLabel.setId(subjectLabelDTO.getId());
        subjectLabel.setIsDeleted(IsDeleteEnum.DELETED.code);
        boolean b= subjectLabelService.update(subjectLabel);
        return Result.ok(b);
    }


    /**
     * 查询分类下标签
     */
    @PostMapping("/queryLabelByCategoryId")
    public Result<List<SubjectLabelDTO>> queryLabelByCategoryId(@RequestBody SubjectLabelDTO subjectLabelDTO) {
        subjectLabelDTO.validatorQueryParam(subjectLabelDTO);
        SubjectLabel subjectLabel = SubjectLabelDTOConverter.INSTANCE.convertDtoToEntity(subjectLabelDTO);
        List<SubjectLabel>subjectLabelList=subjectLabelService.queryLabel(subjectLabel);
        List<SubjectLabelDTO> subjectLabelDTOList = SubjectLabelDTOConverter.INSTANCE.convertEntityToDtoList(subjectLabelList);
        return Result.ok(subjectLabelDTOList);
    }


}
